<template>
	<view>
		<custom-navigation-bar title="form表单"></custom-navigation-bar>
		<view class="main">
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						姓名
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入内容" @input="updateName" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						性别
					</view>
					<view class="form-item-countent">
						<radio-group @change="updateSex" style="margin-top: 20rpx;">
							<radio value="0" class="custom-radio" checked />男
							<radio value="1" class="custom-radio" />女
						</radio-group>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						电话
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入内容" @input="updatePhone" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						申请区域
					</view>
					<view class="form-item-countent">
						<position-picker class="position-picker" @update-region="regionChange"></position-picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						详细地址
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入内容" @input="updatePosition" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						申请社区
					</view>
					<view class="form-item-countent">
						<picker @change="communityChange" :range="communityArray">
							<view style="padding: 20rpx;background-color: white;">{{ community }}</view>
						</picker>
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						身份证号
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入内容" @input="updateIdCard" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<uni-file-picker @select="handleIdSelect" @delete="handleIdDelete" limit="2"
						title="请上传身份证反正面照片(最多2张)"></uni-file-picker>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						开户行
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入银行名称" @input="updateBankName" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view class="form-item-1">
					<view class="form-item-lable">
						银行卡号
					</view>
					<view class="form-item-countent">
						<input type="text" class="form-item-input" placeholder="请输入银行卡号" @input="updateBankCard" />
					</view>
					<view class="form-item-right">
						<image src="/static/gengduo@3x(1).png" class="form-item-image"></image>
					</view>
				</view>
			</view>
			<view class="form-item">
				<view style="width: 84%;float: left;margin-left: 8%;">
					<view class="btn" @click="submit">按钮</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		defineComponent
	} from 'vue';
	import http from '../../utils/http';
	import {
		generateApplicationId,
		getCurrentTimestamp,
		generateTime
	} from '../../utils/timeUtils';
	// 提取字段
	const applicationContent = ref({
		userId: getApp().globalData.user.userId,
		userCurrentType: getUserIdentity(),
		applicationType: "assistant",
		name: '', // 姓名
		sex: 0, // 性别
		phone: '', // 联系电话
		province: '',
		city:"",
		district:"",
		position: '', // 详细地址
		community: '', // 社区
		idCard: '', // 身份证号
		bankName: '', // 开户行
		bankCard: '', // 银行卡号
		idImage: [],
		applicationStatus: 0,
		approverUserId: getApp().globalData.user.approverUserId
	});
	const image = ref({
		idCard: [] //身份证正反面照片
	})
	function getUserIdentity() {
		const user = getApp().globalData.user;
		const roles = [{
				key: 'administer',
				label: '平台管理员'
			},
			{
				key: 'cityPartner',
				label: '城市合伙人'
			},
			{
				key: 'shop',
				label: '商家'
			},
			{
				key: 'butler',
				label: '管家'
			},
			{
				key: 'assistant',
				label: '小助手'
			},
			{
				key: 'lawyer',
				label: '律师'
			}
		];
	
		const identities = roles
			.filter(role => user[role.key] === 1)
			.map(role => role.label);
	
		return identities.length > 0 ? '普通用户-' + identities.join('-') : '普通用户';
	}
	// 联系人姓名
	function updateName(e) {
		applicationContent.value.name = e.target.value;
	}
	// 性别
	function updateSex(e) {
		applicationContent.value.sex = e.target.value;
	}
	// 电话
	function updatePhone(e) {
		applicationContent.value.phone = e.target.value;
	}
	// 所在区域
	function regionChange(e) {
		// console.log("position", e[0] + "-" + e[1] + "-" + e[2])
		// applicationContent.value.region = e[0] + "-" + e[1] + "-" + e[2]
		applicationContent.value.province = e[0]
		applicationContent.value.city = e[1]
		applicationContent.value.district = e[2]
		getCommunityList(e[0], e[1], e[2])
	}
	// 详细地址
	function updatePosition(e) {
		applicationContent.value.position = e.target.value;
	}
	const communityArray = ref([])
	const community = ref("请选择社区")
	// 申请的社区
	function communityChange(e) {
		community.value = communityArray.value[e.detail.value]
		applicationContent.value.community = e[0] + "-" + e[1] + "-" + e[2]
	}

	function updateIdCard(e) {
		applicationContent.value.idCard = e.target.value;
	}
	//身份证正面照片
	function handleIdSelect(e) {
		if (e.tempFiles.length == 0) {
			return;
		}
		for (let i in e.tempFiles) {
			image.value.idCard.push(e.tempFiles[i])
		}

	}

	function updateBankName(e) {
		applicationContent.value.bankName = e.target.value
	}

	function updateBankCard(e) {
		applicationContent.value.bankCard = e.target.value
	}
	// 获取社区信息
	function getCommunityList(province, city, district) {
		http.request({
			url: "/api/user/get_community_list",
			method: "POST",
			data: {
				"province": province,
				"city": city,
				"district": district
			}
		}).then((responseData) => {
			if (responseData.code) {
				console.log("community", responseData.data)
				communityArray.value = responseData.data
			} else {
				uni.showToast({
					icon: 'error',
					title: responseData.message,
					duration: 3000
				})
				communityArray.value = []
			}
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			})
		})
	}
	// 上传文件函数
	async function uploadFile(file, fileType) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:8080/utils/upLoadFile',
				filePath: file.path,
				name: 'file', // 文件字段名
				formData: {
					"fileType": "application",
					"fileName":getCurrentTimestamp(),
					"userId": applicationContent.value.userId
				},
				success: (uploadRes) => {
					const res = JSON.parse(uploadRes.data).data;
					applicationContent.value.idImage.push(res)
					resolve();
				},
				fail: (error) => {
					console.log('上传失败', error);
					reject(error);
				}
			});
		});
	}
	async function submit() {
		try {
			console.log("applicationContent", applicationContent.value);
			// 上传身份证图片
			const idCardPromises = image.value.idCard.map(idCardFile => uploadFile(idCardFile, 'idCard'));
		
		
		
			// 等待所有上传操作完成
			await Promise.all([...idCardPromises]);
		
			// 所有上传操作完成后，调用 http.request
			const responseData = await http.request({
				url: "/api/application/insert_application",
				method: "POST",
				data: {
					application: applicationContent.value
				}
			});
			console.log("提交成功", responseData.data);
			uni.showToast({
				icon: "success",
				title: "提交成功",
				duration: 1500,
				complete: function() {
					setTimeout(function() {
						uni.navigateBack({
							delta: 1 // 返回到上一页
						});
					}, 1500); // 延迟 1.5 秒，和 showToast 的 duration 相同
				}
			})
		} catch (err) {
			// 在这里处理上传文件过程中的错误
			console.log("上传文件失败", err);
		}
	}

	function test() {
		console.log("test", applicationContent.value)
		console.log("golbal", getApp().globalData.openid)
	}
</script>

<style>
	@import "./form.scss";
</style>